<template>
  <a-layout class="search-page">
    <a-layout-header class="search-header">
      <div class="search-bar">
        <a-input-search
          v-model:value="searchQuery"
          placeholder="搜索帖子、评论或用户"
          enter-button
          size="large"
          @search="onSearch"
          :loading="loading"
        >
          <template #prefix>
            <search-outlined />
          </template>
        </a-input-search>
      </div>
    </a-layout-header>

    <a-layout>
      <a-layout-sider width="240" class="search-sider">
        <a-card title="搜索过滤" :bordered="false">
          <a-menu
            v-model:selectedKeys="selectedTypes"
            mode="inline"
            @select="handleTypeSelect"
          >
            <a-menu-item key="all">
              <template #icon>
                <global-outlined />
              </template>
              全部结果
            </a-menu-item>
            <a-menu-item key="posts">
              <template #icon>
                <file-text-outlined />
              </template>
              帖子
            </a-menu-item>
            <a-menu-item key="comments">
              <template #icon>
                <comment-outlined />
              </template>
              评论
            </a-menu-item>
            <a-menu-item key="users">
              <template #icon>
                <user-outlined />
              </template>
              用户
            </a-menu-item>
          </a-menu>

          <a-divider />

          <div class="filter-section">
            <h4>时间范围</h4>
            <a-radio-group v-model:value="timeRange" @change="handleTimeChange">
              <a-radio value="all">全部时间</a-radio>
              <a-radio value="day">24小时内</a-radio>
              <a-radio value="week">一周内</a-radio>
              <a-radio value="month">一个月内</a-radio>
            </a-radio-group>
          </div>

          <a-divider />

          <div class="filter-section">
            <h4>排序方式</h4>
            <a-radio-group v-model:value="sortBy" @change="handleSortChange">
              <a-radio value="relevance">相关度</a-radio>
              <a-radio value="time">最新发布</a-radio>
              <a-radio value="hot">最多互动</a-radio>
            </a-radio-group>
          </div>
        </a-card>
      </a-layout-sider>

      <a-layout-content class="search-content">
        <a-card :bordered="false">
          <template #title>
            <span>搜索结果 ({{ total }})</span>
            <a-tag color="blue" class="search-type-tag">
              {{ searchTypeDisplay }}
            </a-tag>
          </template>

          <!-- 搜索结果列表 -->
          <a-list
            :loading="loading"
            :data-source="searchResults"
            item-layout="vertical"
            :pagination="pagination"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <template #actions>
                  <span>
                    <eye-outlined /> {{ item.views }} 浏览
                  </span>
                  <span>
                    <like-outlined /> {{ item.likes }} 点赞
                  </span>
                  <span>
                    <message-outlined /> {{ item.comments }} 评论
                  </span>
                </template>

                <a-list-item-meta>
                  <template #avatar>
                    <a-avatar :src="item.avatar" />
                  </template>
                  <template #title>
                    <router-link :to="item.link" v-html="highlightText(item.title)" />
                  </template>
                  <template #description>
                    <span>{{ item.author }} · {{ formatDate(item.createTime) }}</span>
                  </template>
                </a-list-item-meta>

                <div class="search-result-content" v-html="highlightText(item.content)" />

                <template #extra>
                  <a-space>
                    <a-tag v-if="item.type === 'post'" color="blue">帖子</a-tag>
                    <a-tag v-else-if="item.type === 'comment'" color="green">评论</a-tag>
                    <a-tag v-else-if="item.type === 'user'" color="purple">用户</a-tag>
                  </a-space>
                </template>
              </a-list-item>
            </template>

            <template #empty>
              <a-empty
                v-if="!loading"
                description="暂无搜索结果"
              >
                <template #description>
                  <span>
                    未找到与 "{{ searchQuery }}" 相关的{{ searchTypeDisplay }}
                    <br />
                    建议：
                    <ul>
                      <li>请检查输入是否正确</li>
                      <li>尝试使用其他关键词</li>
                      <li>选择其他过滤条件</li>
                    </ul>
                  </span>
                </template>
              </a-empty>
            </template>
          </a-list>
        </a-card>
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  SearchOutlined,
  GlobalOutlined,
  FileTextOutlined,
  CommentOutlined,
  UserOutlined,
  EyeOutlined,
  LikeOutlined,
  MessageOutlined
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'

// 路由相关
const route = useRoute()
const router = useRouter()

// 搜索状态
const searchQuery = ref('')
const loading = ref(false)
const total = ref(0)
const searchResults = ref<any[]>([])

// 过滤条件
const selectedTypes = ref(['all'])
const timeRange = ref('all')
const sortBy = ref('relevance')

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  onChange: (page: number) => {
    pagination.value.current = page
    fetchSearchResults()
  }
})

// 计算属性
const searchTypeDisplay = computed(() => {
  const typeMap: Record<string, string> = {
    all: '内容',
    posts: '帖子',
    comments: '评论',
    users: '用户'
  }
  return typeMap[selectedTypes.value[0]]
})

// 获取搜索结果
const fetchSearchResults = async () => {
  loading.value = true
  try {
    // 模拟API调用，实际项目中应替换为真实API
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟数据
    const mockData = {
      items: Array(10).fill(null).map((_, index) => ({
        id: index + 1,
        title: `搜索结果 ${index + 1} 包含 "${searchQuery.value}"`,
        content: `这是一个包含 "${searchQuery.value}" 关键词的搜索结果内容示例。这里是更多的内容描述，可能会很长...`,
        author: `用户${Math.floor(Math.random() * 1000)}`,
        avatar: `https://randomuser.me/api/portraits/${index % 2 ? 'men' : 'women'}/${index + 1}.jpg`,
        createTime: new Date(Date.now() - Math.random() * 10000000000).toISOString(),
        views: Math.floor(Math.random() * 1000),
        likes: Math.floor(Math.random() * 100),
        comments: Math.floor(Math.random() * 50),
        type: ['post', 'comment', 'user'][Math.floor(Math.random() * 3)],
        link: `/post/${index + 1}`
      })),
      total: 56
    }
    
    searchResults.value = mockData.items
    total.value = mockData.total
    pagination.value.total = mockData.total
  } catch (error) {
    message.error('搜索请求失败，请稍后重试')
    console.error('Search error:', error)
  } finally {
    loading.value = false
  }
}

// 监听路由参数变化
watch(
  () => route.query,
  (newQuery) => {
    if (newQuery.q) {
      searchQuery.value = newQuery.q as string
      selectedTypes.value = [newQuery.type as string || 'all']
      timeRange.value = newQuery.time as string || 'all'
      sortBy.value = newQuery.sort as string || 'relevance'
      pagination.value.current = parseInt(newQuery.page as string || '1')
      fetchSearchResults()
    }
  },
  { immediate: true }
)

// 搜索处理函数
const onSearch = async (value: string) => {
  if (!value.trim()) {
    message.warning('请输入搜索关键词')
    return
  }
  
  updateRouteQuery({
    q: value,
    page: '1'
  })
}

// 过滤条件处理函数
const handleTypeSelect = ({ key }: { key: string }) => {
  updateRouteQuery({ type: key, page: '1' })
}

const handleTimeChange = () => {
  updateRouteQuery({ time: timeRange.value, page: '1' })
}

const handleSortChange = () => {
  updateRouteQuery({ sort: sortBy.value, page: '1' })
}

// 更新路由查询参数
const updateRouteQuery = (updates: Record<string, string>) => {
  router.push({
    query: {
      ...route.query,
      ...updates
    }
  })
}

// 高亮搜索关键词
const highlightText = (text: string) => {
  if (!searchQuery.value || !text) return text
  const regex = new RegExp(`(${searchQuery.value})`, 'gi')
  return text.replace(regex, '<span class="highlight">$1</span>')
}

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 组件挂载时执行
onMounted(() => {
  if (route.query.q) {
    searchQuery.value = route.query.q as string
    fetchSearchResults()
  }
})
</script>

<style lang="less" scoped>
.search-page {
  min-height: 100vh;
  background: #f0f2f5;

  .search-header {
    background: #fff;
    padding: 16px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    height: auto;
    line-height: normal;

    .search-bar {
      max-width: 800px;
      margin: 0 auto;
    }
  }

  .search-sider {
    background: transparent;
    padding: 24px 0;

    :deep(.ant-card) {
      background: transparent;
    }

    .filter-section {
      margin: 16px 0;

      h4 {
        margin-bottom: 12px;
        color: rgba(0, 0, 0, 0.85);
      }

      .ant-radio-group {
        display: flex;
        flex-direction: column;
        gap: 8px;
      }
    }
  }

  .search-content {
    padding: 24px;

    .search-type-tag {
      margin-left: 12px;
    }

    :deep(.ant-list-item) {
      padding: 24px;
      transition: all 0.3s;

      &:hover {
        background: rgba(0, 0, 0, 0.02);
      }

      .search-result-content {
        margin: 16px 0;
        color: rgba(0, 0, 0, 0.65);
      }
    }
  }
}

:deep(.highlight) {
  background-color: #ffd591;
  padding: 0 2px;
  border-radius: 2px;
}

@media screen and (max-width: 768px) {
  .search-page {
    .search-sider {
      width: 100% !important;
      max-width: 100% !important;
      padding: 12px;
    }

    .search-content {
      padding: 12px;
    }
  }
}
</style> 